package com.huifaapp.mall.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.PendingPayAdapter;
import com.huifaapp.mall.adapter.PendpayAdaptertwo;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.base.bean.PayBean;
import com.huifaapp.mall.bean.PendingPayBean;
import com.huifaapp.mall.bean.event.OrderStatusEventMessage;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.AlipayUtils;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.view.TakePhotoPopWin;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.squareup.okhttp.Request;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * 待付款
 * A simple {@link Fragment} subclass.
 */
public class PendingPayFragment extends Fragment implements  TakePhotoPopWin.OnItemClickListener{

    private RecyclerView Pendpay;
    private List<PendingPayBean.OrderListBean> list;
    private PendingPayAdapter pendingPayAdapter;
    private PendpayAdaptertwo pendpayAdaptertwo;
    private TakePhotoPopWin mPop;
    private String orderNo;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_pending_pay, container, false);
        initView(view);
        Pendpay.setLayoutManager(new LinearLayoutManager(getActivity()));
        EventBus.getDefault().register(this);
        return view;
    }

    @Subscribe
    public void onEvent(OrderStatusEventMessage orderStatusEventMessage){
        Log.d("NIHAOA", "onEvent: " + orderStatusEventMessage.toString());
        for (int i = 0;i<list.size();i++){
            if (list.get(i).getOrderNo().equals(orderStatusEventMessage.getOrderNo())) {
                list.remove(i);
                pendingPayAdapter.notifyDataSetChanged();
                break;
            }
        }
    }
    private boolean isGetData = false;
    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        //   进入当前Fragment
        if (enter && !isGetData) {
            isGetData = true;
            load();
            //   这里可以做网络请求或者需要的数据刷新操作
        } else {
            isGetData = false;
        }
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isGetData) {
            load();
            //   这里可以做网络请求或者需要的数据刷新操作
            isGetData = true;
        }
    }
    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        isGetData = false;
        super.onDestroy();
    }

    @Override
    public void onStart() {
        super.onStart();
        load();
    }

    private void initView(View view) {
        Pendpay = (RecyclerView) view.findViewById(R.id.pendpay_rv);
        Log.e("代支付url-------------",(ApiManager.BASE_NIUPAI_URL+"orders/notpayed"+"?token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&token="+AUniqueIdentifier.getDeviceId(getActivity())));

        mPop = new TakePhotoPopWin(getActivity());
        mPop.setOnItemClickListener(this);
        mPop.setFocusable(false);


    }
    private void load(){
        OkHttpUtils.get().url(ApiManager.BASE_NIUPAI_URL+"orders/notpayed")
                .addParams("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                .addParams("appId", AUniqueIdentifier.getDeviceId(getActivity()))
                //token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3 ")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {


                        try {

                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray orderList = jsonObject.getJSONArray("orderList");
                            Log.e("FH",orderList+"");
                            initData(response);
                        } catch (JSONException e) {
                            Log.e("FH","HHH");
                        }
                    }
                });
    }
    public void initData(String response) {

        final Gson gson = new Gson();
        PendingPayBean pendingPayBean = gson.fromJson(response, PendingPayBean.class);
        list = pendingPayBean.getOrderList();
        pendingPayAdapter = new PendingPayAdapter(getActivity(), list);
        Pendpay.setAdapter(pendingPayAdapter);

        //三个按钮的监听事件
        pendingPayAdapter.setOnItemClickListener(new PendingPayAdapter.OnItemClickListener() {
            @Override
            public void onContactSeller(int position) {     //联系买家
                Intent intent = new Intent(getActivity(), com.huifaapp.mall.activity.Homefragment.WebActivity.class);
                intent.putExtra("url","http://chat56.live800.com/live800/chatClient/chatbox.jsp?companyID=937587&configID=154412&jid=1486640810");
                startActivity(intent);
            }

            @Override
            public void onCancelOrder(final int position) {   //取消订单
                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("是否需要删除？")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                final String order = list.get(position).getOrderNo();
                                OkHttpUtils.post().url(ApiManager.BASE_NIUPAI_URL+"orders/cancelorders")
                                        .addParams("token",SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN))
                                        .addParams("appId",AUniqueIdentifier.getDeviceId(getActivity()))
                                        .addParams("orderNo",order)
                                        .build()
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onError(Request request, Exception e) {
                                                ToastUtils.showShort("删除失败");
                                            }

                                            @Override
                                            public void onResponse(String response) {
                                                Log.e("HB",response);
                                                try {
                                                    JSONObject jsonObject = new JSONObject(response);
                                                    String code =  jsonObject.getString("code");
                                                    if (code.equals("10000"))
                                                    {
                                                        ToastUtils.showShort("删除成功");
                                                        list.remove(position);
                                                        pendingPayAdapter.notifyDataSetChanged();



                                                    }else {
                                                        ToastUtils.showShort("删除失败");
                                                    }

                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }


                                            }
                                        });

                            }
                        }).create();
                alertDialog.show();



            }

            @Override
            public void onPayment(int position) {   //付款
                double totalprice = list.get(position).getTotalprice(); //商品总价
                orderNo = list.get(position).getOrderNo();
                Contig.orderNo=orderNo;
                mPop.showAtLocation(getActivity().findViewById(R.id.main_view_pendingpay), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
            }

        });
//        pendpayAdaptertwo.setOnItemClickListener(new PendpayAdaptertwo.OnItemClickListenertwo() {
//            @Override
//            public void OnItem(View view, int position) {
//                Intent intent = new Intent(getActivity(), WaitPayActivity.class);
//                startActivity(intent);
//            }
//        });
    }

    String method = "1"; //支付方式 1 微信支付，2支付宝支付。
    @Override
    public void setOnItemClick(View v) {
        switch (v.getId()){
            case R.id.tv_true_pay:
//                params = getWindow().getAttributes();
//                params.alpha=1f;
//                getWindow().setAttributes(params);
                mPop.dismiss();
                pay(orderNo);
                break;
            case R.id.ll_ye_pay:
//
                break;
            case R.id.ll_wx_pay:
                method="1";
                break;
            case R.id.ll_zfb_pay:
                method="2";
                break;
            case R.id.ll_fq_pay:

                break;
            case R.id.ll_ye_pay_no:

                break;
            case R.id.iv_pay_close:
                mPop.dismiss();
                break;

        }
    }
    private void pay(String orderNo){

        if ("1".equals(method)) {
            String url = ApiManager.WXPAY_PAY+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(getActivity())+"&orderNo="+orderNo;
//            String url = ApiManager.WXPAY_PAY+"?token=201712291124171334f3ed61d93e05404b8dc78f10c4770cf8&appId=D7B72681-8205-4C8F-8CCB-142C448203E3"
//                    +"&orderNo="+orderNo;
            Log.e("WEB", "路径Pay=====" + url);
            HttpUtils http = new HttpUtils();
            http.send(HttpRequest.HttpMethod.POST, url, new RequestCallBack<String>() {
                @Override
                public void onLoading(long total, long current, boolean isUploading) {
//                  testTextView.setText(current + "/" + total);
                    Log.e("数据", "数据-------" + current + "/" + total);
                }

                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
//                    textView.setText(responseInfo.result);

                    try {
                        Log.e("数据123", "数据payd-------" + responseInfo.result);
                        Gson gson = new Gson();
                        PayBean list = gson.fromJson(responseInfo.result, PayBean.class);

                        if(list.getCode().equals("10000")) {
                            Log.e("数据123", "数据list-------" + list);
                            IWXAPI mWxApi = WXAPIFactory.createWXAPI(getActivity(), list.getData().getAppid(), true);
                            mWxApi.registerApp(list.getData().getAppid());
                            PayReq req = new PayReq();
                            req.appId = list.getData().getAppid();
                            req.partnerId = list.getData().getMch_id();
                            req.prepayId = list.getData().getPrepay_id();
                            req.nonceStr = list.getData().getNonce_str();
                            req.timeStamp = list.getData().getTimestamp();
                            req.packageValue ="Sign=WXPay";
                            req.sign = list.getData().getSign();
                            //在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
                            Log.e("数据123", "数据payd-------" + req);
                            mWxApi.sendReq(req);
                            Log.e("数据123", "mWxApi-------" + mWxApi);
                        }else{
                            Toast.makeText(getActivity(),list.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }catch (JsonSyntaxException e){
                        Toast.makeText(getActivity(),"未知错误",Toast.LENGTH_LONG).show();
                    }

                }
                @Override
                public void onStart() {
                }

                @Override
                public void onFailure(HttpException error, String msg) {
                }
            });
        } else if ("2".equals(method)) {
            new AlipayUtils(getActivity()).getAlipaySignature(orderNo,SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN),AUniqueIdentifier.getDeviceId(getActivity()));
        } else {
            ToastUtils.showShortSafe("获取信息失败!");
        }
    }

}
